package com.eternal.util.tree;


import com.eternal.util.tree.entity.Tree;

import java.util.ArrayList;
import java.util.List;

/**
 * 构建Tree
 */
public class BuildTree {

    /**
     * <p>  构造树 </p>
     *
     * @Description: TODO
     * @Param
     * @Return
     * @Author Eternal
     * @Date 2018/10/28 22:23
     */
    public static <T> List<Tree<T>> build(List<Tree<T>> nodes) {
        if (nodes == null) {
            return null;
        }
        List<Tree<T>> topNodes = new ArrayList<Tree<T>>();
        for (Tree<T> children : nodes) {
            String pid = children.getParentId();
            if (pid == null || "".equals(pid) || pid.equals("0")) {
                topNodes.add(children);
                continue;
            }
            for (Tree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChildren().add(children);
                    parent.setAttributes(parent.getAttributes());
                    continue;
                }
            }
        }
        return topNodes;

    }

    private static boolean aa = true;

    /**
     * <p>  展开父级树 </p>
     *
     * @Description: TODO
     * @Param
     * @Return
     * @Author Eternal
     * @Date 2018/10/28 22:22
     */
    public static <T> List<Tree<T>> expandParentTree(List<Tree<T>> nodes, String id) {
        List<Tree<T>> newnodes = new ArrayList<>();
        String parentId = "";
        for (Tree<T> tree : nodes) {
            if (id.equals(tree.getId())) {
                parentId = tree.getParentId();
                tree.setExpand(true);
                aa = true;
            }
            newnodes.add(tree);
        }
        while (aa) {
            if (null != parentId) {
                expandParentTree(newnodes, parentId);
            } else {
                aa = false;
                break;
            }
        }

        return newnodes;
    }


}